<template>
  <!-- 查询栏 -->
  <div class="query">
    <QueryForm :form="form" v-model="queryData" @handleQuery="handleQuery" />
  </div>
  <!-- 表单栏 -->
  <div class="table">
    <BaseTable
      v-loading="tableLoading"
      :columns="columns"
      :data="dataList"
      :pager="pager"
      @handleCurrentChange="handleCurrentChange"
      @handleAction="handleAction"
    >
      <template v-slot:action>
        <el-button type="primary" @click="handleCreate">新增</el-button>
      </template>
    </BaseTable>
    <!-- 弹窗 -->
    <el-dialog
      :title="action == 'add' ? '新增' : '编辑'"
      v-model="showModal"
      :before-close="handleClose"
    >
      <el-form
        ref="dialogForm"
        :rules="rules"
        :model="dataForm"
        label-width="100px"
      >
        <el-form-item label="标题" prop="name">
          <el-input
            v-model="dataForm.name"
            placeholder="请输入标题"
          />
        </el-form-item>
        <el-form-item label="简介" prop="desc">
          <el-input
            v-model="dataForm.desc"
            placeholder="请输入简介"
          />
        </el-form-item>
        <el-form-item label="分类ID" prop="cid">
          <!-- <el-input
            v-model="dataForm.cid"
            placeholder="请输入分类ID"
          /> -->
          <el-select v-model="dataForm.cid" placeholder="分类">
            <el-option-group
              v-for="group in categoryList"
              :key="group.name"
              :label="group.name"
            >
              <el-option
                v-for="item in group.children"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="发布用户" prop="uname">
          <el-input
            v-model="dataForm.uname"
            placeholder="请输入发布用户"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor v-model="dataForm.content"></editor>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dataForm.status">
            <el-option :value="0" label="禁用"></el-option>
            <el-option :value="1" label="启用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否置顶" prop="is_top">
          <el-select v-model="dataForm.status">
            <el-option :value="0" label="否"></el-option>
            <el-option :value="1" label="是"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="展示图片" prop="head_img">
            <UploadImage
              :limit="1"
              v-model="dataForm.head_img"
              @change="validParams('head_img')"
            />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, toRaw } from "vue";
import {
  queryBlogTopicListByPage,
  blogTopicAdd,
  blogTopicEdit,
  blogTopicDel,
} from "@/api/blogTopic";
import { ElMessage } from "element-plus";
import Editor from "@/components/Editor.vue";
import UploadImage from "@/components/UploadImage.vue";
import { queryBlogCategoryList } from "@/api/blogCategory";
/****************************************** data ******************************************/

// 参数
const pager = reactive({
  page: 1,
  limit: 10,
  total: 0,
});
// 渲染数据
const dataList = ref(<any>[]);

// 编辑动作：add,edit,delete
const action = ref("");

// 弹窗变量
const showModal = ref(false);

// 弹窗ref
const dialogForm = ref(<any>null);

// 所有分类数据
const categoryList = ref(<any>[]);

// 表单loading
const tableLoading = ref(false);

// 初始化用户表单对象
const queryData = ref(<any>{ status: null });

// 表格提交数据
interface DataModel {
  id?: number,
  name: string,
  uname: string,
  status: number,
  content: string,
  cid: number,
  desc: string,
  head_img: string,
}
const dataForm = ref(<DataModel>{
  status: 1
});

// 生成查询form结构数据
const form = [
  {
    type: "input",
    label: "标题",
    model: "name",
    placeholder: "请输入标题",
  }
];

// 定义动态表格的格式
const columns = reactive([
  {
    label: "标题",
    prop: "name",
  },
  {
    type: "img",
    label: "展示图片",
    prop: "head_img",
  },
  {
    label: "简介",
    prop: "desc",
    width: 200
  },
  {
    label: "用户名字",
    prop: "uname",
  },
  {
    label: "分类",
    prop: "cname",
    width: 120
  },
  {
    type: "tag",
    label: "状态",
    prop: "status",
    formatter: (row: any, column: any, value: number) => {
      return {
          0: "禁用",
          1: "启用",
      }[value];
    },
    dict: {
        0: "danger", 
        1: "success", 
    },
  },
  {
    type: "switch",
    label: "状态操作",
    prop: "status",
    checked: 1,
  },
  {
    label: "阅读数",
    prop: "view_count",
  },
  {
    label: "收藏数",
    prop: "like_count",
  },
  {
    label: "评论数",
    prop: "comment_count",
  },
  {
    label: "是否置顶",
    prop: "is_top",
  },
  {
    type: "action",
    label: "操作",
    width: 140,
    list: [{ text: "编辑", type: "text" }, { text: "删除",confirm: true  }],
  },
]);

// 弹窗校验规则
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入标题",
      trigger: "blur",
    },
  ],
  desc: [
    {
      required: true,
      message: "请输入简介",
      trigger: "blur",
    },
  ],
  content: [
    {
      required: true,
      message: "请输入内容",
      trigger: "blur",
    },
  ],
  cid: [
    {
      required: true,
      message: "请输入分类ID",
      trigger: "blur",
    },
  ],
  status: [
    {
      required: true,
      message: "请输入状态#0-禁用;1-启用",
      trigger: "blur",
    },
  ],
  head_img: [
    {
      required: true,
      message: "请上传head_img",
      trigger: "change",
    },
  ],
});

/****************************************** 生命周期函数 ******************************************/
onMounted(() => {
  handleQuery();
  getCategoryList();
});

/****************************************** method ******************************************/

const getCategoryList = async () => {
    let data = (await queryBlogCategoryList({})).data;
    categoryList.value = data;
};

const validParams = (fieldName: string) => {
  dialogForm.value.validateField(fieldName, () => null);
};
// 查询
const handleQuery = async () => {
  tableLoading.value = true;
  let data = (await queryBlogTopicListByPage({ ...pager, ...queryData.value })).data;
  dataList.value = data.rows;
  pager.total = data.count;
  tableLoading.value = false;
};

// 分页事件处理
const handleCurrentChange = (current: number) => {
  pager.page = current;
  handleQuery();
};

// 新增
const handleCreate = () => {
  action.value = "add";
  showModal.value = true;
};

// 操作
const handleAction = async ({ text, row }: any) => {
  if (text === "编辑") {
    action.value = "edit";
    showModal.value = true;
    await nextTick();
    Object.assign(dataForm.value, row);
  } else if (text === "删除") {
    await blogTopicDel({ id: row.id });
    ElMessage({ message: "删除成功", type: "success" });
    handleQuery();
  }else if (text === "状态操作") {
    let status;
    if (row.status === 1) {
      status = 0;
    } else {
      status = 1;
    }
    await blogTopicEdit({ id: row.id, status });
    ElMessage({ message: "更新成功", type: "success" });
    handleQuery();
  }
};

// 取消
const handleClose = () => {
  showModal.value = false;
  handleReset(dialogForm);
};

// 重置
const handleReset = (form: any) => {
  form.value.resetFields();
};

// 提交
const handleSubmit = () => {
  let res: any;
  dialogForm.value.validate(async (valid: boolean) => {
    if (valid) {
      let params = toRaw(dataForm.value);
      let model:DataModel = {
          name: params.name,
          uname: params.uname,
          status: params.status,
          content: params.content,
          desc: params.desc,
          head_img: params.head_img,
          cid: params.cid
      }
      if (action.value === "add") {
        res = await blogTopicAdd(model);
      } else if (action.value === "edit") {
        model.id = params.id
        res = await blogTopicEdit(model);
      }
      if (res && res.code === 200) {
        showModal.value = false;
        ElMessage({ message: "操作成功", type: "success" });
        handleReset(dialogForm);
        handleQuery();
      }
    }
  });
};
</script>

<style lang="scss" scoped></style>
